<template>
  <!--  数据清洗字段管理  -->
  <div class="dictMapping app-container">
    <el-row :gutter="20" class="full-row">
      <!--部门数据-->
      <div class="full-height" style="padding: 20px; overflow: auto">
        <div class="head-container">
          <el-select v-model="groupType" placeholder="请选择分组类型" @change="handleChange">
            <el-option
              v-for="item in typeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>
        <div class="head-container" style="flex: 1; overflow: auto">
          <el-tree
            ref="tree"
            :expand-on-click-node="false"
            default-expand-all
            :data="deptOptions"
            :props="defaultProps"
            current-node-key="1"
            :filter-node-method="filterNode"
            node-key="id"
            highlight-current
            @node-click="handleNodeClick"
          >
            <span slot-scope="{ node, data }" style="width: 80%; display: flex">
              <span style="margin-right: 10px">
                <img
                  :src="
                    data.isLeaf == 0
                      ? require('../../../assets/images/folder.png')
                      : require('../../../assets/images/zuzhi.png')
                  "
                  style="margin-right: 10px"
                >
              </span>
              <span v-if="!data.showInput" class="custom-tree-node">
                <span v-if="data.dictKey && data.dictKey.length < 12">{{ data.dictKey }}</span>
                <el-tooltip v-else class="item" effect="dark" :content="data.dictKey" placement="top">
                  <span>{{ data.dictKey }}</span>
                </el-tooltip>
                <i>
                  <el-button
                    v-if="data.isLeaf == 0"
                    type="text"
                    size="mini"
                    icon="el-icon-plus"
                    @click.stop="() => append(data)"
                  />
                  <el-button
                    type="text"
                    size="mini"
                    icon="el-icon-edit"
                    @click.stop="() => editNode(node, data)"
                  />
                  <!-- <el-button
                    type="text"
                    size="mini"
                    icon="el-icon-delete"
                    @click.stop="() => remove(node, data)"
                  >
                  </el-button>-->
                </i>
              </span>
              <span v-else class="custom-tree-node">
                <el-input
                  v-model="data.dictKey"
                  placeholder="不能为空"
                  size="mini"
                  class="innerput"
                  maxlength="100"
                  @blur.capture="judgeBlur(node,data)"
                  @focus="saveDictkey(node,data.dictKey)"
                />
                <i>
                  <el-button type="text" size="mini" @click.stop="() => sureNode(node, data)">确定</el-button>

                  <el-button type="text" size="mini" @click.stop="() => remove(node, data)">取消</el-button>
                </i>
              </span>
            </span>
          </el-tree>
        </div>
      </div>
      <!--用户数据-->
      <div class="user">
        <el-form
          v-show="showSearch"
          ref="queryForm"
          :model="queryParams"
          size="small"
          :inline="true"
          label-width="150px"
          @submit.native.prevent
        >
          <el-form-item label="字典名称" prop="dictKey">
            <el-input
              v-model="queryParams.dictKey"
              placeholder="请输入字典名称"
              clearable
              style="width: 240px"
              @keyup.enter.native="allDict"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="allDict">查询</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mt2">
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="mini"
              :disabled="isLeaf == 1"
              @click="handleAdd"
            >新增</el-button>
          </el-col>
        </el-row>

        <HkTable
          style="flex: 1;"
          :loading="loading"
          :table-data="dictList"
          :table-columns="tableList"
          :selection="true"
          :operate="true"
          :total="total"
          :show-index="true"
          :table-height="80"
          :query-params="queryParams"
          @handleSelectionChange="handleSelectionChange"
          @changePage="getList"
        >
          <template #operate="scope">
            <el-button size="mini" type="text" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button size="mini" type="text" @click="handleUphold(scope.row)">字典维护</el-button>
            <el-button size="mini" type="text" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </HkTable>
      </div>
    </el-row>

    <!-- 编辑对话框 -->

    <AddDictData ref="editRef" :form="form" :title="title" @handleSubmit="handleSubmit" />

    <uphold-dialog
      :id="upholdId"
      ref="upholdRef"
      title="字典维护"
      :dict-code="dictCode"
      :group-type="groupType"
    />
    <!-- 用户导入对话框 -->
  </div>
</template>

<script>
import UpholdDialog from './mappingDictData'
import { dictTree, delDict, dictRules, allDict, addDict, updateDict } from '@/api/milkyway/ruleDict'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import HkTable from '@/components/Hk-Table/index'
import AddDictData from './addDictData'

export default {
  name: 'DictMapping',

  components: {
    UpholdDialog,
    HkTable,
    AddDictData
  },
  data() {
    return {
      // 是否是添加状态
      appendState: false,
      // 字典维护所需要的
      upholdId: '',
      dictCode: '',
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      // 总条数
      total: 0,
      // 部门列表
      deptId: '',
      // 右侧新增是否可点击
      isLeaf: '',
      // 部门列表
      deptOptions: [],
      // 字典表格数据
      dictList: [],
      // 弹出层标题
      title: '',
      // 查询参数
      queryParams: {
        current: 1,
        size: 10
      },
      // 表单参数
      form: {
        type: this.groupType,
        dictKey: undefined,
        dictValue: undefined,
        dictCode: undefined,
        sort: undefined,
        parentId: this.deptId
      },

      //  表格
      tableList: [
        { label: '字典名称', param: 'dictKey' },
        { label: '字典值', param: 'dictValue' },
        { label: '字典编码', param: 'dictCode' }
      ],
      defaultProps: {
        children: 'children',
        label: 'dictKey'
      },

      // 列信息
      columns: [
        { key: 0, label: `用户编号`, visible: true },
        { key: 1, label: `用户名称`, visible: true },
        { key: 2, label: `用户昵称`, visible: true },
        { key: 3, label: `部门`, visible: true },
        { key: 4, label: `手机号码`, visible: true },
        { key: 5, label: `状态`, visible: true },
        { key: 6, label: `创建时间`, visible: true }
      ],
      typeOptions: [
        {
          label: '映射字典',
          value: '1'
        },
        {
          label: '规则字典',
          value: '2'
        }
      ],
      groupType: '1',

      // 表单校验
      rules: {}
    }
  },
  watch: {
    groupType(newValue, oldValue) {
      this.getTreeselect()
      this.allDict()
    },
    deptId() {}
  },
  created() {
    this.getTreeselect()
    this.allDict()
  },

  methods: {
    judgeBlur(node, data) {
      // this.remove(node, dictKey)
    },
    // 暂存dictkey
    saveDictkey(node, dictKey) {
      if (!node.tempDictkey) {
        node.tempDictkey = dictKey
      }
    },
    // 增加树节点
    append(data) {
      this.appendState = true
      const newChild = { name: '', children: [] }
      if (!data.children) {
        this.$set(data, 'children', [])
      }
      newChild.showInput = true
      newChild.remove = true
      newChild.isLeaf = 0
      data.children.unshift(newChild)
    },
    // 移除树节点
    remove(node, data) {
      if (!node.data.dictKey && !data.remove) {
        this.$message.error('名称不能为空')
      }
      if (node.tempDictkey) {
        node.data.dictKey = node.tempDictkey
        node.tempDictkey = ''
      }
      this.appendState = false
      if (data.remove) {
        const parent = node.parent
        const children = parent.data.children || parent.data
        const index = children.findIndex(d => d.id === data.id)
        if (data.id) {
          this.$modal
            .confirm('是否确认删除所选项？')
            .then(function() {
              return delDict(data.id)
            })
            .then(() => {
              this.$modal.msgSuccess('删除成功')
              children.splice(index, 1)
            })
            .catch(error => {
              console.log(error)
            })
        } else {
          children.splice(index, 1)
        }
      } else {
        data.showInput = false
        data.remove = true
      }
    },
    // 确定添加树节点
    sureNode(node, data) {
      this.appendState = false
      const datas = {
        parentId: node.parent.data.id,
        isLeaf: 0,
        dictKey: data.dictKey,
        type: this.groupType
      }

      if (data.dictKey) {
        if (!data.id) {
          addDict(datas).then(res => {
            this.$message.success('新增成功')
            this.getTreeselect()
          })
        } else {
          updateDict({ ...datas, id: data.id }).then(res => {
            this.$message.success('修改成功')
            this.getTreeselect()
          })
        }
        data.showInput = false
        data.remove = true
      } else {
        this.$message.error('名称不能为空')
      }
    },
    // 重命名node
    editNode(node, data) {
      data.remove = false
      data.showInput = true
    },
    // 获取所有字典名称
    allDict() {
      this.queryParams.current = 1
      this.queryParams.scrollToTop = true
      allDict({ ...this.queryParams, type: this.groupType }).then(res => {
        this.dictList = res.list
        this.total = res.total
        this.loading = false
        this.queryParams.scrollToTop = false
      })
    },

    /** 查询列表 */
    getList(val) {
      if (this.appendState) return
      else {
        this.loading = true
        this.queryParams = {
          ...this.queryParams,
          ...val,
          id: this.deptId,
          type: this.groupType
        }

        dictTree(this.queryParams).then(res => {
          this.dictList = res.list
          this.total = res.total
          this.loading = false
        })
      }
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      // this.allDict()
      this.getList()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id || this.ids
      this.$modal
        .confirm('是否确认删除所选数据项？')
        .then(function() {
          return delDict(id)
        })
        .then(() => {
          this.$modal.msgSuccess('删除成功')
          this.getList()
          this.getTreeselect()
        })
        .catch(error => {
          console.log(error)
        })
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      return new Promise((resolve, reject) => {
        dictTree({ type: this.groupType }).then(res => {
          this.deptOptions = res.map(item => {
            return {
              children: this.treeChild(item.children),
              dictKey: item.dictKey,
              id: item.id,
              showInput: false,
              remove: true,
              isLeaf: item.isLeaf
            }
          })

          this.deptId = this.deptId || this.deptOptions[0].id
          resolve(this.deptId)
        })
      })
    },
    // 递归数据
    treeChild(item) {
      if (item) {
        return item.map(i => {
          return {
            children: this.treeChild(i.children),
            dictKey: i.dictKey,
            id: i.id,
            showInput: false,
            remove: true,
            isLeaf: i.isLeaf
          }
        })
      } else return
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 节点单击事件
    handleNodeClick(data) {
      return new Promise((resolve, reject) => {
        this.isLeaf = data.isLeaf

        this.deptId = data.id
        resolve(this.isLeaf)
      }).then(() => {
        this.getList()
      })
    },
    // 右侧新增完成
    handleSubmit() {
      this.getList()
      this.getTreeselect()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.form = {
        type: this.groupType,
        dictKey: undefined,
        dictValue: undefined,
        dictCode: undefined,
        sort: undefined,
        parentId: this.deptId
      }
      this.$refs.editRef.open = true
      this.title = '添加'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const id = row.id || this.ids
      dictRules(id).then(res => {
        this.form = res
        this.form.type = this.groupType
      })
      this.$refs.editRef.open = true
      this.title = '编辑'
    },

    //  字典分组
    handleChange(groupType) {},
    // 打开字典维护
    handleUphold(data) {
      return new Promise((resolve, reject) => {
        this.upholdId = data.id
        this.dictCode = data.dictCode
        resolve(this.upholdId)
      }).then(() => {
        this.$refs.upholdRef.show()
      })
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep .targetTable .el-table{
  overflow: hidden !important;
}
.app-container {
  padding: 0;
}
.user {
  width:calc(100% - 440px);
  overflow: hidden;
  padding: 20px;
  flex: 1;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.full-row {
  width: 100%;
  display: flex;
  margin: 0 !important;
  height: 100%;

  .full-height {
    height: 100%;
    display: flex;
    width: 400px;
    flex-direction: column;
    border-right: 1px solid rgba(0, 0, 0, 0.08);
  }
  .custom-tree-node {
    width: calc( 100% - 40px );
    display: flex;
    align-items: center;
    justify-content: space-between;
    span {
    width: calc( 100% - 40px );
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }
}
.innerput{
  height:30px;
  line-height: 30px !important;
  width: 100px;
  font-size: 14px;
  padding: 0 5px;
}
</style>
<style lang="scss">
.dictMapping {
  width: 100%;
  height: 100%;

  // .el-tree
  //   > .el-tree-node
  //   > .el-tree-node__content
  //   > .el-icon-caret-right:before {
  //   background-image: url(../../../assets/images/folder.png) !important;
  //   width: 20px;
  //   height: 20px;
  //   background-repeat: no-repeat;
  //   background-size: contain;
  // }
  // .el-icon-caret-right::before {
  //   display: none;
  // }
  .el-tree {
    margin-top: 20px;
    font-size: 14px;
  }
}
</style>
